package im.composer.media.sound.codec;

import java.io.IOException;

import javax.sound.sampled.AudioFormat;

import org.tritonus.share.sampled.FloatSampleBuffer;
import org.tritonus.share.sampled.file.AudioOutputStream;

public class FloatOutputStream implements AudioOutputStream, AutoCloseable {

	private final AudioOutputStream out;
	private transient byte[] tempBuffer = null;

	public FloatOutputStream(AudioOutputStream out) {
		this.out = out;
	}

	public void write(FloatSampleBuffer buffer) throws IOException {
		write(buffer, 0, buffer.getSampleCount());
	}

	public synchronized void write(FloatSampleBuffer buffer, int offset, int sampleCount) throws IOException {
		int bSize = buffer.getByteArrayBufferSize(getFormat(), sampleCount);
		if(tempBuffer==null||tempBuffer.length<bSize){
			tempBuffer = new byte[bSize];
		}
		buffer.convertToByteArray(offset, sampleCount, tempBuffer, 0, getFormat());
		write(tempBuffer,0,bSize);
	}

	public AudioFormat getFormat() {
		return out.getFormat();
	}

	public long getLength() {
		return out.getLength();
	}

	public int write(byte[] abData) throws IOException {
		return write(abData, 0, abData.length);
	}

	public int write(byte[] abData, int nOffset, int nLength) throws IOException {
		return out.write(abData, nOffset, nLength);
	}

	public void close() throws IOException {
		out.close();
	}

}
